﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;


using PracticeSimple.Models;
using BusinessObjects;

namespace PracticeSimple.Controllers
{
    public class EncounterController : Controller
    {
        //
        // GET: /Encounter/

        public ActionResult Index(int id)
        {
            EncounterModel model = new EncounterModel();
            model.encounter = DataLayer.GetRepo.Encounter().Select(id);
            model.patient = DataLayer.GetRepo.Patient().Select(model.encounter.PatientID);
            model.vitals = DataLayer.GetRepo.Vital().SelectAll();
            return View(model);
        }

        public JsonResult SaveEncounter(string encounterJSON)
        {
            Encounter encounter = new JavaScriptSerializer().Deserialize<Encounter>(encounterJSON);
            encounter.FacilityID = (int)Session["FacilityID"];

            DataLayer.GetRepo.Encounter().Save(encounter);

            return Json(true);
        }

        public JsonResult GetEncounterVitals(int encounterID)
        {
            List<EncounterVital> encounterVitals = DataLayer.GetRepo.EncounterVital().GetVitalsForEncounter(encounterID);

            return Json(new JavaScriptSerializer().Serialize(encounterVitals));
             
        }

        public JsonResult SaveAllEncounterVitals(string vitalsJSON)
        {
            List<EncounterVital> encounterVitals = new JavaScriptSerializer().Deserialize<List<EncounterVital>>(vitalsJSON);
            List<EncounterVital> savedEncounterVitals = new List<EncounterVital>();
            foreach (EncounterVital ev in encounterVitals)
            {
                ev.CreatedDate = DateTime.Now;
                ev.CreatedBy = Session["UserID"].ToString();

                savedEncounterVitals.Add(SaveEncounterVital(ev));
            }

            return Json(new JavaScriptSerializer().Serialize(savedEncounterVitals));
        }

        private EncounterVital SaveEncounterVital(EncounterVital ev)
        {
           return DataLayer.GetRepo.EncounterVital().Save(ev);
        }
    }
}
